<template>
<form-dialog
    :title="title"
    :visible="visible"
    width="30%"
    @handleClose="handleClose"
  >
    <template #content>
      <el-form ref="form" :model="formData" :rules="formRule" label-width="100px" v-loading="loading">
        <el-form-item :label="$t('common.name')" prop="name">
          <el-input v-model="formData.name" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.description')" prop="description">
          <el-input type="textarea" maxlength="200" @keyup.enter.native="submit" show-word-limit v-model="formData.description"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialog>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialog from '../../../components/Dialog/formDialog.vue';
export default Vue.extend({
  components: {
    FormDialog
  },
  props: {
    submitMethod: {
      type: Function,
      default() {
        return (formData: any) => Promise.resolve();
      }
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      title: '',
      formData: {
        name: "",
        description: ""
      },
      formRule: {
        name: [
          { required: true, message: this.$t('user.nameRequired'), trigger: 'blur' },
          { max: 50, message: this.$t('message.nameLengthRule'), trigger: 'blur' }
        ],
        description: [
          { max: 200, message: this.$t('policy.message.descriptionLength'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeDialog() {
      
    },
    init(formData: any) {
      
      this.title = (this as any).$t('objectActive.rename') + ' ' + (this as any).$t('objectType.desktop_client') + ' ' + formData.name
      if (formData) {
        this.formData = Object.assign({}, formData);
        this.visible = true;
      } else {
        this.formData = {
          name: "",
          description: ""
        };
        this.visible = true;
      }
      if((this as any).$refs['form']) {
        (this as any).$refs['form'].clearValidate();
      }
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
          this.loading = true;
          this.submitMethod(this.formData).then(() => {
            this.handleClose();
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    handleClose() {
      this.formData = {
        name: "",
        description: ""
      };
      (this as any).$refs['form'].clearValidate();
      this.loading = false;
      this.visible = false;
    }
  }
})
</script>
<style lang="scss" scoped>

</style>
